<template>
	<view
		style="background-color: #F0F2F5;width: 100%;height: 100vh;display: flex;align-items: center; flex-direction: column;">
		<!-- <view
			style="width: 90%;border-radius: 10px;background-color: white;display: flex;flex-direction: row;margin-top: 15px;align-items: center;padding-top: 10px;padding-bottom: 10px;">
			<text style="display: flex;justify-content: center;margin-left: 10px;">蓝牙</text>
			<view style="width: 85%; display: flex;justify-content: center;align-items: center;">
				<switch style="flex: 1;text-align: right;zoom:0.8" @change="switchChange" :checked="isBluetooth">
				</switch>
			</view>
		</view> -->

		<view @click="disconnect()"
			style="width: 90%;border-radius: 10px;background-color: white;display: flex;flex-direction: column;margin-top: 15px;justify-content: center;padding-top: 10px;padding-bottom: 10px;">
			<text style="margin-left: 10px;">已连接设备</text>
			<view style="display: flex;flex-direction: row;margin-left: 20px;margin-top: 5px;">
				<text>{{deviceName}}</text>
				<text style="margin-left: 10px;font-size: 8pt;margin-top: 5px;color: gray;">{{deviceId}}</text>
			</view>
		</view>

		<view
			style="width: 90%;border-radius: 10px;background-color: white;display: flex;flex-direction: column;margin-top: 15px;">
			<view
				style="display: flex;flex-direction: row;margin-left: 10px;height: 44px;justify-content: center;align-items: center;padding-right: 10px;">
				<text style="flex: 1;text-align: left;">设备信息</text>

				<button @click="$noMultipleClicks(closeBluetoothAdapter)" type="primary"
					style="height: 80%;display: flex; align-items: center;">刷新</button>
				<!-- <text  >刷新</text>
				<image src="../../static/refresh.png" style="width: 20px;height: 20px;margin-right: 10px;"
					@click="search"></image> -->
			</view>

			<view v-for="(item,index) in blueDeviceList" @click="initBlue(item,index)"
				style=" display: flex;flex-direction: row;margin-left: 10px; align-items: center;justify-content: center;height: 66px;">
				<view style="display: flex;flex-direction: column;">
					<text>{{ item.name }}</text>
					<text style="font-size: 8pt;margin-top: 2px;color: gray;">{{ item.deviceId }}</text>
				</view>

				<view
					style="height: 100%; flex: 1;justify-content: right; display: flex; flex-direction: row;align-items: center;">
					<view style="display: flex;flex-direction: row;align-items: baseline;">
						<view class="iconRssi" style="height: 10px;"
							:style="{'background-color': item.RSSI >= -100? '#2697F9':'#D8D8D8'}"></view>
						<view class="iconRssi" style="height: 13.5px;"
							:style="{'background-color': item.RSSI >= -70? '#2697F9':'#D8D8D8'}"></view>
						<view class="iconRssi" style="height: 17px;"
							:style="{'background-color': item.RSSI >= -60? '#2697F9':'#D8D8D8'}"></view>
						<view class="iconRssi" style="height: 20.5px;"
							:style="{'background-color': item.RSSI >= -50? '#2697F9':'#D8D8D8'}"></view>
						<view class="iconRssi" style="height: 24px;"
							:style="{'background-color': item.RSSI >= -30? '#2697F9':'#D8D8D8'}"></view>
					</view>

					<text style="margin-left: 5px; margin-right: 10px;">{{item.RSSI}}dbm</text>
				</view>

				<text v-if="item.isConnect" style="margin-right: 15px;color: red;font-size: 9pt;">已连接</text>
				<text v-else-if="!item.isConnect" style="margin-right: 15px;color: gray;font-size: 9pt;">未连接</text>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		unique,
		EnquirieswriteBLECharacteristicValue,
	} from '../../comment/dataUtils.js'

	export default {
		data() {
			return {
				isBluetooth: true,
				blueDeviceList: [],
				flag: true,
				deviceName: '',
				deviceId: '',
				uuid: "",
				characteristics: [],
				noClick: true,

				RSSI: '',
				timer: null,
				timer1: null,
				// isRefresh:false,
				newDeviceId: '0'
			}
		},

		onNavigationBarButtonTap(e) {

			// let that = this;
			// if (that.noClick) {
			// 	// 第一次点击
			// 	that.noClick = false;
			// 	console.log("我是导航栏右侧的文字", e);
			// 	if (e.text == "开始搜索") {
			// 		this.search()
			// 	} else if (e.text == "停止搜索") {
			// 		this.stop()
			// 	}
			// 	setTimeout(() => {
			// 		that.noClick = true;
			// 	}, 1000)
			// } else {
			// 	// 这里是重复点击的判断
			// }
		},

		onShow() {
			var that = this

			that.deviceName = getApp().globalData.deviceName
			that.deviceId = getApp().globalData.deviceId
			console.log("可见~~~~~~~~~~", that.deviceId,that.newDeviceId)
			if (that.deviceId != '') {
				this.getBLEDeviceRSSI()
			}
			that.openBluetoothAdapter()
		},

		onUnload() {
			this.stop()
			if (this.timer) { //注销定时器
				console.log('注销定时器timer', this.timer)
				clearInterval(this.timer)
				this.timer = null;
			}

			// if (this.timer1) { //注销定时器
			// 	console.log('注销定时器timer1',this.timer1)
			// 	clearInterval(this.timer1)
			// 	this.timer1 = null;
			// }
			//console.log("停止搜索---111111");
		},

		onHide() {

		},

		onLoad() {
			var that = this
			that.NoticeConnection()
		},

		methods: {

			getBLEDeviceRSSI() {
				var that = this
				this.timer = setInterval(() => {
					uni.getBLEDeviceRSSI({
						deviceId: this.deviceId,
						success(res) {
							that.blueDeviceList.forEach(item => {
								if (item.deviceId == that.deviceId) {
									item.RSSI = res.RSSI
								}
							})
							console.log(res);
						},

						fail: (err) => {
							console.log(err);
							if (this.timer) { //注销定时器
								console.log('注销定时器timer', this.timer)
								clearInterval(this.timer)
								this.timer = null;
							}
						}
					})
				}, 1500)
			},

			openBluetoothAdapter() {
				var that = this

				uni.openBluetoothAdapter({
					success: function(res) {

						console.log("是否开启蓝牙", res)
						that.isBluetooth = true
						that.search()
					},
					fail: function(res) {
						console.log(res);
						if (res.errCode === 10001) {
							that.isBluetooth = false
							// 未开启弹出提示框
							uni.showToast({
								title: "请打开蓝牙",
								icon: 'error',
								duration: 3000
							})
						}
					},

					complete: function(res) {

					},
				});
			},

			navigatorButton() {
				// var pages = getCurrentPages();
				// var page = pages[pages.length - 1];
				// var currentWebview = this.$mp.page.$getAppWebview();
				// var tn = currentWebview.getStyle().titleNView;
				// //在data中添加flag默认为true
				// console.log("180-------------", tn, this.flag)
				// //修改按钮文本文本
				// if (this.flag) {
				// 	tn.buttons[0].text = '停止搜索';
				// 	currentWebview.setStyle({
				// 		titleNView: tn
				// 	});
				// 	this.flag = false
				// } else {
				// 	tn.buttons[0].text = '开始搜索';
				// 	currentWebview.setStyle({
				// 		titleNView: tn
				// 	});
				// 	this.flag = true
				// }
			},

			switchChange(e) {
				var that = this
				console.log(e)
				const BluetoothAdapter = plus.android.importClass('android.bluetooth.BluetoothAdapter'); // 引入Java 蓝牙类
				const blueadapter = BluetoothAdapter.getDefaultAdapter(); //拿到默认蓝牙适配器方法
				if (e.target.value) {
					if (blueadapter != null) {
						blueadapter.enable();
					}

					setTimeout(function() {
						uni.openBluetoothAdapter({
							success: function(res) {
								console.log("开启蓝牙成功", res);
								that.search()
							},
							fail: function(res) {
								console.log("开启蓝牙失败", res);
							}
						})
					}, 1000);
				} else {
					if (blueadapter != null) {
						return blueadapter.disable();
					}
				}
			},


			search() {
				var that = this;
				that.blueDeviceList = []
				uni.showLoading({
					title: '搜索中...'
				})

				uni.startBluetoothDevicesDiscovery({
					allowDuplicatesKey: true,
					//interval:0,
					success: function(res) {
						//that.navigatorButton()
						console.log("搜索设备---", res)
						uni.onBluetoothDeviceFound(function(el) {
							//找到对应蓝牙设备名字
							//	var rssi = (devices.devices[0].RSSI + 100) / 10
							//that.blueDeviceList.push(el.devices[0])

							el.devices.forEach((device, index) => {
								if (device.name.indexOf("HSST") != -1) {
									that.blueDeviceList.push(device)
									console.log("设备列表==", device)
								}
							})

							//设备列表去重
							for (let i = 0; i < that.blueDeviceList.length; i++) {
								// let num=0;
								for (let j = i + 1; j < that.blueDeviceList.length; j++) {
									if (that.blueDeviceList[i].deviceId == that.blueDeviceList[j]
										.deviceId) {
										that.blueDeviceList[i].RSSI = that.blueDeviceList[j].RSSI
										// num++
										that.blueDeviceList.splice(j, 1); //去重
									}
								}
							}
						});
						uni.hideLoading()
					},

					fail: (res) => {
						//that.navigatorButton()
						// var title = '搜索失败，请重试'
						// if(res.errCode == 10008) {
						// 	title = '系统错误，扫描过于频繁'
						// }
						// uni.showToast({
						// 	icon:'error',
						// 	title: title
						// })
						console.log("搜索失败", res)
						uni.hideLoading()
					},

					complete: function(res) {
						uni.hideLoading()
						that.getBluetoothDevices()
						console.log("搜索完成===", res)
					}
				});
			},


			stop() {
				var that = this
				uni.stopBluetoothDevicesDiscovery({
					success(res) {
						//that.navigatorButton()
						console.log("停止搜索---", res);
					},
					complete: function(res) {}
				});
			},

			initBlue(devices, index) {
				let that = this;

				if (devices.isConnect) {
					uni.showToast({
						title: '设备已连接'
					})
					return false
				}

				that.disconnect()

				console.log(devices)
				uni.showLoading({
					title: '正在连接中...',
				})

				uni.createBLEConnection({
					deviceId: devices.deviceId,
					success: (res) => {
						uni.hideLoading()
						this.newDeviceId = '1'
						that.deviceName = devices.name
						that.deviceId = devices.deviceId
						//that.blueDeviceList[index].isConnect = true
						//that.$forceUpdate();

						//是否连接
						that.blueDeviceList.forEach((item, mIndex) => {
							// this.isLink.push(0);
							if (mIndex == index) {
								item.isConnect = true
							} else {
								item.isConnect = false
							}
						})

						getApp().globalData.deviceName = devices.name
						getApp().globalData.deviceId = devices.deviceId
						console.log("连接成功---", JSON.stringify(res), that.blueDeviceList[index]);

						uni.showToast({
							title: '设备连接成功'
						})
						
						this.getBLEDeviceRSSI()

						//需延时连接，不然会报错
						setTimeout(function() {
							uni.getBLEDeviceServices({
								deviceId: that.deviceId,
								success: (res) => {
									console.log("获取蓝牙设备所有服务", res);

									// if (res.services.length != 0) {
									// 	if (res.services[2] != null) {
									// 		that.uuid = res.services[2].uuid;
									// 	} else if (res.services[1] != null) {
									// 		that.uuid = res.services[1].uuid;
									// 	} else {
									// 		that.uuid = res.services[0].uuid;
									// 	}
									// }
									//app的uuid
									//that.uuid = res.services[2].uuid;
									//小程序的uuid
									that.uuid = res.services[0].uuid;
									that.getInfo();
								},
							});
						}, 1000);
					},

					fail: function(res) {
						console.log('设备连接失败')
						console.log(res)
						uni.hideLoading()
						// uni.showToast({
						// 	title: '设备连接失败',
						// 	icon: 'error'
						// })
					},
					
					complete: function(res) {
						console.log('设备连接完成',res)
						//that.newDeviceId = '0'
					}
				});
				
				if(that.newDeviceId == '0') {
					setTimeout(function() {
						console.log('设备连接超时',that.newDeviceId)	
						if(that.newDeviceId == '0') {
							uni.hideLoading()
							uni.showToast({
								title: '连接超时，请重试',
								icon:'error',
								duration:2000
							})
							that.closeBluetoothAdapter()
						}else {
							that.newDeviceId = '0'
						}
					}, 6000);
				}
			},

			getBluetoothDevices() {
				var that = this
				uni.getBluetoothDevices({
					success: (res) => {

						//添加设备
						res.devices.forEach((item) => {
							if (item.name.indexOf("HSST") != -1) {
								that.blueDeviceList.push(item)
							}
						})
						console.log("获取蓝牙设备成功:" + JSON.stringify(that.blueDeviceList));
						//是否连接
						that.blueDeviceList.forEach((item, index) => {
							item['isConnect'] = false
							if (item.deviceId == that.deviceId) {
								item.isConnect = true
							} else {
								item.isConnect = false
							}
						})

						//设备列表去重
						for (let i = 0; i < that.blueDeviceList.length; i++) {

							// let num=0;
							for (let j = i + 1; j < that.blueDeviceList.length; j++) {
								if (that.blueDeviceList[i].deviceId == that.blueDeviceList[j].deviceId) {
									// num++
									//that.blueDeviceList[i].RSSI = that.blueDeviceList[j].RSSI
									that.blueDeviceList.splice(j, 1); //去重
								}
							}
						}
					},
				});
			},

			disconnect() {
				let that = this;
				//this.isRefresh = false

				uni.closeBLEConnection({
					deviceId: that.deviceId,
					success: (res) => {
						console.log("断开连接", res);
						//是否连接
						that.blueDeviceList.forEach((item, mIndex) => {
							// this.isLink.push(0);
							if (item.deviceId == that.deviceId) {
								item.isConnect = true
							} else {
								item.isConnect = false
							}
						})
					},
				});

				//that.closeBluetoothAdapter()
			},

			closeBluetoothAdapter() {
				let that = this;
				//this.isRefresh = b
				that.stop()
				uni.closeBluetoothAdapter({
					success: function(res) {
						console.log("closeBluetoothAdapter ==>res:", res);

						setTimeout(function() {
							that.openBluetoothAdapter()
						}, 200)

					},
					fail: function(error) {
						console.log("closeBluetoothAdapter ==>error:", error);
					}
				})
			},

			// 监听蓝牙连接状态
			NoticeConnection() {
				var _this = this;
				uni.onBLEConnectionStateChange((res) => {
					console.log('开始监听蓝牙状态', res)

					if (!res.connected) {
						_this.blueDeviceList.forEach((item, index) => {
							if (item.deviceId == _this.deviceId) {
								item.isConnect = false
							}
						})
						//_this.closeBluetoothAdapter()
						console.log('连接已断开', _this.newDeviceId);
						_this.deviceName = "暂未连接设备"
						_this.deviceId = ''
						getApp().globalData.deviceName = _this.deviceName
						getApp().globalData.deviceId = _this.deviceId
						getApp().globalData.isDone = false

						// if (_this.newDeviceId == '1') {
							
						// } else {
						// 	uni.showToast({
						// 		title: '连接断开请重连',
						// 		icon: 'error',
						// 	})
						// }
					}
				})
			},

			getInfo() {
				let that = this;
				uni.getBLEDeviceCharacteristics({
					deviceId: that.deviceId,
					serviceId: that.uuid,
					success: (res) => {
						that.characteristics = res.characteristics;
						getApp().globalData.characteristics = that.characteristics;
						getApp().globalData.uuid = that.uuid
						console.log("获取--------", res);
					},
					fail: (res) => {
						console.log("失败1--------", res);
					},
				});


				setTimeout(function() {
					uni.setBLEMTU({
						deviceId: that.deviceId,
						mtu: 512,
						success: (res) => {
							console.log("设置传输字符成功--------", res);
							setTimeout(function() {
								that.updateNotify()
							}, 1000)
						},
						fail: (res) => {
							console.log("设置传输字符失败--------", res);
							setTimeout(function() {
								that.updateNotify()
							}, 1000)
						},
					})
				}, 1000)
			},

			updateNotify() {
				let that = this
				let characteristicId = ""
				
				try{
					for (var i = 0; i < that.characteristics.length; i++) {
						if (that.characteristics[i].properties.notify == true) {
							characteristicId = that.characteristics[i].uuid
							throw Error()
						}
					}
				}catch(e){
					console.log(e)
				}
				uni.notifyBLECharacteristicValueChange({
					deviceId: that.deviceId,
					serviceId: that.uuid,
					characteristicId: characteristicId,
					state: true,
					success: (res) => {
						console.log(res);
						if (res.errMsg == "notifyBLECharacteristicValueChange:ok") {
							console.log("开启消息监听------", that.uuid,characteristicId);
							// uni.hideLoading();
							// this.cut = false;
							// this.BLEValue();
							getApp().globalData.deviceName = that.deviceName
							getApp().globalData.deviceId = that.deviceId
						}
					},
					fail: (res) => {
						console.log("失败1--------", res);
					},

					complete: (res) => {

					}
				});
			},
		}
	}
</script>

<style>
	.iconRssi {
		width: 3px;
		background-color: #D8D8D8;
		margin-left: 2px;
		display: flex;
	}
</style>